package com.esb.bootstrap;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.lang.reflect.Proxy;

import com.esb.rpc.proxy.InvokerInvocationHandler;
import com.esb.transport.channel.Channel;
import com.esb.transport.channel.NettyChannel;
import com.esb.transport.handler.DefaultHandler;
import com.esb.transport.handler.codec.MessageDecoder;
import com.esb.transport.handler.codec.MessageEncoder;
import com.esb.transport.protocal.FastjsonCodec;

public class Client implements Protocol{
	
	private Channel channel;
	private EventLoopGroup group;
	
	public Client(){
		group = new NioEventLoopGroup(20);
	}
	
	@SuppressWarnings("unchecked")
	public <T> T registerService(Class<T> serviceClazz){
		if(channel==null)throw new RuntimeException("请先调用connect方法!");
		channel.isOpen();
		
		return (T) Proxy.newProxyInstance(Thread.currentThread()
				.getContextClassLoader(), new Class<?>[] { serviceClazz },
				new InvokerInvocationHandler(channel));
	}

	public void connect(String ip, int port) throws Exception {
		// Configure the client.
		Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(NioSocketChannel.class)
         .option(ChannelOption.TCP_NODELAY, true)
         .handler(new ChannelInitializer<SocketChannel>() {
             @Override
             public void initChannel(SocketChannel ch) throws Exception {
                 ch.pipeline().addLast(
                         new LoggingHandler(LogLevel.INFO),
                         new MessageEncoder(new FastjsonCodec()),
                         new MessageDecoder(new FastjsonCodec()),
                         new DefaultHandler());
             }
         });

        // Start the client.
        ChannelFuture f = b.connect(ip, port).sync();
        channel = NettyChannel.wrapperChannel(f.channel());
	}
	
	public void close(){
		group.shutdownGracefully();
	}
	
}
